package util

import (
	"github.com/json-iterator/go"
	"math"
	"nspel/entity"
	"nspel/nspel"
	"strconv"
)

var json = jsoniter.ConfigCompatibleWithStandardLibrary

func GetReportsListAdministrator(provinceId int64, cityId int64, areaId int64, schoolName string, joinYear int64, pageSize int64, currentPage int64) (count int64, reports []entity.Report, err error) {
	report := new(entity.Report)
	ormEng := nspel.GetOrmEngine().QueryTable(report.TableName())
	hashKey := ""
	if provinceId != 0 || cityId != 0 || areaId != 0 || schoolName != "" || joinYear != 0 {
		var schools []entity.School
		_, schools, err = GetSchoolsListAdministrator(provinceId, cityId, areaId, schoolName, joinYear, math.MaxInt64, 1)
		if err != nil {
			return
		}
		schoolIds := make([]int64, len(schools))
		for i := 0; i < len(schools); i++ {
			schoolIds[i] = schools[i].Id
		}
		if len(schoolIds) == 0 {
			schoolIds = []int64{math.MinInt64}
		}
		ormEng = ormEng.Filter("school_id__in", schoolIds)
		var idStr string
		idStr, err = json.MarshalToString(schoolIds)
		if err != nil {
			return
		}
		hashKey += "schoolIdIn" + idStr + "."
	} else {
		hashKey = "all"
	}
	count, err = report.CustomCount(&ormEng, hashKey+"count")
	if err != nil {
		return
	}
	hashKey += "pageSize[" + strconv.FormatInt(pageSize, 10) + "]."
	hashKey += "currentPage[" + strconv.FormatInt(currentPage, 10) + "]"
	offset := (currentPage - 1) * pageSize
	ormEng = ormEng.Limit(pageSize, offset)
	reports, err = report.CustomSelect(&ormEng, hashKey)
	if err != nil {
		return
	}
	return
}

func GetReportsListArea(areaId int64, joinYear int64, schoolId int64, pageSize int64, currentPage int64) (count int64, reports []entity.Report, err error) {
	report := new(entity.Report)
	ormEng := nspel.GetOrmEngine().QueryTable(report.TableName())
	hashKey := ""
	if areaId != 0 || joinYear != 0 || schoolId != 0 {
		var schools []entity.School
		_, schools, err = GetSchoolsListArea(areaId, joinYear, schoolId, math.MaxInt64, 1)
		if err != nil {
			return
		}
		schoolIds := make([]int64, len(schools))
		for i := 0; i < len(schools); i++ {
			schoolIds[i] = schools[i].Id
		}
		if len(schoolIds) == 0 {
			schoolIds = []int64{math.MinInt64}
		}
		ormEng = ormEng.Filter("school_id__in", schoolIds)
		var idStr string
		idStr, err = json.MarshalToString(schoolIds)
		if err != nil {
			return
		}
		hashKey += "schoolIdIn" + idStr + "."
	}
	count, err = report.CustomCount(&ormEng, hashKey+"count")
	if err != nil {
		return
	}
	hashKey += "pageSize[" + strconv.FormatInt(pageSize, 10) + "]."
	hashKey += "currentPage[" + strconv.FormatInt(currentPage, 10) + "]"
	offset := (currentPage - 1) * pageSize
	ormEng = ormEng.Limit(pageSize, offset)
	reports, err = report.CustomSelect(&ormEng, hashKey)
	if err != nil {
		return
	}
	return
}
